import { StyleSheet, View, FlatList, Image, TouchableOpacity } from 'react-native'
import React, { useEffect, useState } from 'react'
import { Text } from 'react-native-paper'
import { reqCategoryTop10 } from '@/api/shop'
import type { GoodsItem, ResCategoryTop10 } from '@/types/goods'
import { useNavigation } from '@react-navigation/native'
import { StackNavigationProp } from '@react-navigation/stack'
import { useGetDataList } from '@/hook/useGetDataList'
import { API } from '@/api/shop'

import icon_search from '@/assets/images/icon_search.png'
import icon_shop_car from '@/assets/images/icon_shop_car.png'
import icon_orders from '@/assets/images/icon_orders.png'
import icon_menu_more from '@/assets/images/icon_menu_more.png'

const Shop = () => {
  // 分类前十
  const [category, setCategory] = useState<ResCategoryTop10>()
  // 获取商品前十
  const getCategory = async () => {
    const res = await reqCategoryTop10()
    setCategory(res)
  }
  // 获取商品列表
  const getDataList = useGetDataList<GoodsItem[]>(API.GOODS_LIST, 'GET')

  useEffect(() => {
    const getData = async () => {
      await Promise.all([getCategory(), getDataList.getDataList()])
    }
    getData()
  }, [])

  // 渲染列表头部
  const ListHeaderComponent = () => {
    const styles = StyleSheet.create({
      categoryContainer: {
        width: '100%',
        flexDirection: 'row',
        flexWrap: 'wrap',
        paddingHorizontal: 10,
        paddingTop: 20,
        backgroundColor: '#fff'
      },
      category: {
        width: '20%',
        flexDirection: 'column',
        alignItems: 'center',
        marginBottom: 20
      },
      img: {
        width: 42,
        height: 60
      },
      imgTxt: {
        fontSize: 14
      }
    })
    return (
      <View style={styles.categoryContainer}>
        {category?.map(item => (
          <View style={styles.category} key={item.id}>
            <Image source={{ uri: item.image }} style={styles.img}></Image>
            <Text style={styles.imgTxt}>{item.name}</Text>
          </View>
        ))}
      </View>
    )
  }
  // 渲染商品列表
  const renderItem = ({ item }: { item: GoodsItem }) => {
    const styles = StyleSheet.create({
      goodsItem: {
        flex: 1,
        borderRadius: 6,
        overflow: 'hidden',
        backgroundColor: '#fff',
        marginTop: 8
      },
      img: {
        width: '100%',
        height: 200
      },
      title: {
        paddingHorizontal: 10,
        fontSize: 16,
        marginTop: 14
      },
      priceLayout: {
        paddingHorizontal: 10,
        marginTop: 16,
        marginBottom: 10,
        flexDirection: 'row',
        alignItems: 'center'
      },
      priceTxt: {
        fontSize: 20
      },
      originPriceTxt: {
        marginLeft: 10,
        textDecorationLine: 'line-through',
        color: '#666'
      }
    })
    return (
      <View style={styles.goodsItem}>
        <Image source={{ uri: item.image }} style={styles.img}></Image>
        <Text style={styles.title}>{item.title}</Text>
        <View style={styles.priceLayout}>
          {/* 现价 */}
          <Text style={styles.priceTxt}>￥{item.price}</Text>
          {/* 原价 */}
          {item.originPrice && <Text style={styles.originPriceTxt}>￥{item.originPrice}</Text>}
        </View>
      </View>
    )
  }
  // 渲染商品尾部
  const ListFooterComponent = () => {
    const styles = StyleSheet.create({
      footer: {
        width: '100%',
        height: 50,
        alignItems: 'center',
        justifyContent: 'center'
      }
    })
    return (
      <View style={styles.footer}>
        <Text>{getDataList.finish ? '没有更多了~' : '正在加载...'}</Text>
      </View>
    )
  }

  // 滚动触底的回调
  const onEndReached = () => {
    // 获取下一页数据
    getDataList.getDataList()
  }

  const navigation = useNavigation<StackNavigationProp<any>>()
  // 点击去往搜索商品页面
  const gotoSearchGoods = () => {
    navigation.navigate('SearchGoods')
  }
  return (
    <View style={styles.root}>
      {/* 顶部 */}
      <View style={styles.header}>
        {/* 搜索 */}
        <TouchableOpacity style={styles.searchLayout} activeOpacity={0.7} onPress={gotoSearchGoods}>
          <View style={styles.searchLayout}>
            <Image source={icon_search} style={styles.iconSearch}></Image>
            <Text style={styles.searchTxt}>小米 14</Text>
          </View>
        </TouchableOpacity>
        <Image style={styles.iconMenu} source={icon_shop_car}></Image>
        <Image style={styles.iconMenu} source={icon_orders}></Image>
        <Image style={styles.iconMenu} source={icon_menu_more}></Image>
      </View>
      {/* 列表 */}
      <FlatList
        style={{ flex: 1, backgroundColor: '#fafafafa', paddingHorizontal: 6 }}
        data={getDataList.dataList}
        extraData={category}
        renderItem={renderItem}
        ListHeaderComponent={ListHeaderComponent}
        numColumns={2}
        columnWrapperStyle={{ columnGap: 6 }}
        keyExtractor={(item, index) => `${item.id}-${index}`}
        refreshControl={getDataList.refreshControl()}
        onEndReachedThreshold={0.1}
        onEndReached={onEndReached}
        ListFooterComponent={ListFooterComponent}
      ></FlatList>
    </View>
  )
}

export default Shop

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: '#fff'
  },
  header: {
    width: '100%',
    height: 46,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10
  },
  searchLayout: {
    flex: 1,
    height: 32,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10
  },
  iconSearch: {
    width: 24,
    height: 24,
    resizeMode: 'contain',
    tintColor: '#929292'
  },
  searchTxt: {
    marginLeft: 8
  },
  iconMenu: {
    width: 30,
    height: 30,
    resizeMode: 'contain',
    marginLeft: 12
  }
})
